//
//  FMDBTool.m
//  JiaDianMao
//
//  Created by zwm on 15/11/3.
//  Copyright © 2015年 yjtc. All rights reserved.
//

#import "FMDBTool.h"
static FMDatabase *_db;
static NSArray *_dateBaseArray;
static int _i;

@implementation FMDBTool
//建表
+(void)openDataBase{
    //打开数据库
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"userInformation.db"];
    _db = [FMDatabase databaseWithPath:path];
    if([_db open]){
        [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS userInformation(id integer PRIMARY KEY,userid text,username text,email text,password text,nickname text,mobile text,avatar text,validflag text,score text,feeaccount text,deviceid text,devicetype text,lastloginversion text,lastlogintime text,imgurl0 text,imgurl1 text,state text,birthday text,imgurl2 text,sex text,token text)"];
    }
}

//插入数据
+(void)insertDataBaseWithKey:(NSString *)key value:(NSString *)value{
    if([_db open]){
        
        NSString *insertSql1= [NSString stringWithFormat:
                               @"INSERT INTO userInformation ('%@') VALUES ('%@')",
                               key, value];
        [_db executeUpdate:insertSql1];
    }
}

//得到数据字典集
+(NSMutableDictionary *)selectDataBase{
    NSMutableDictionary *userInforDic = [[NSMutableDictionary alloc]init];
    _dateBaseArray = [NSArray arrayWithObjects:@"userid",@"username",@"email",@"password",@"nickname",@"mobile",@"avatar",@"validflag",@"score",@"feeaccount",@"deviceid",@"devicetype",@"lastloginversion",@"lastlogintime",@"imgurl0",@"imgurl1",@"state",@"birthday",@"imgurl2",@"sex",@"token", nil];
    _i = 0;
    if([_db open]){
        
    // 得到结果集
        FMResultSet *set = [_db executeQuery:@"SELECT * FROM userInformation;"];
    // 不断往下取数据
        while (set.next) {
            NSString *key = [_dateBaseArray objectAtIndex:_i];
            NSString *str = [set stringForColumn:key];
            if(str.length == 0){
                [userInforDic setObject:@"" forKey:key];
            }else{
                [userInforDic setObject:str forKey:key];
            }
    
            if(_i < _dateBaseArray.count-1){
                _i++;
            }else{
                _i = 0;
            }
        }
    }

    return userInforDic;
}

//删除数据
+(void)deleteDataBase{
    if([_db open]){
        [_db executeUpdate:@"DELETE FROM userInformation"];
    }
}
@end


